// 第三方模拟获取授权码路由
import express, { Request, Response } from 'express';
import { ThirdPartyAuth } from  '../auth-mock/ThirdPartyAuth'
import fs from 'fs';
import path from 'path';

const mockAuthRouter = express.Router();
mockAuthRouter.use(express.json());

// 定义统一响应格式
interface ApiResponse {
  status: 'success' | 'error';
  message?: string;
  data?: any;
  errors?: any[];
}

// 辅助函数：从brand-config.json获取所有品牌配置
function getAllBrandConfigs() {
  const brandConfigPath = path.join(__dirname, '../../../brand-config.json');
  return JSON.parse(fs.readFileSync(brandConfigPath, 'utf-8'));
}

/**
 * 获取授权码
 * 请求参数:
 * {
 *   "userId": "用户ID",
 *   "brand" : "品牌名"
 * }
 */
mockAuthRouter.post('/getAuthorizationCode', async (req: Request, res: Response): Promise<void> => {
  const { userId, brand } = req.body;

  // 验证必填参数
  if (!userId || !brand ){
    res.status(400).json({
       status: 'error',
       code: 400,
       message: '缺少必要的请求头: userId或brand',
     } as ApiResponse);
     return;
  }

  try {
    const brands = getAllBrandConfigs();
    const brandConfig = brands[brand.toLowerCase()]; // 不区分大小写匹配

    // 验证品牌是否配置
    if (!brandConfig) {
      res.status(401).json({
        status: 'error',
        code: 401,
        message: `品牌 '${brand}' 未配置，应用认证失败`,
      });
      return;
    }

    const { app_id, app_secret } = brandConfig;
    const thirdPartyAuth = new ThirdPartyAuth(app_id, app_secret);

    // 生成授权码
    const authCode = await thirdPartyAuth.getAuthorizationCode(userId);

    // 成功响应
    res.json({
      status: 'success',
      code: 200,
      data: {
        authorizationCode: authCode.code,
        createdAt: authCode.createdAt,
      },
      message: '授权码生成成功'
    });
    return;

  } catch (err: any) {
    console.error('获取授权码失败:', err);

    // 更精确的错误处理
    let statusCode = 500;
    let errorMessage = '服务器内部错误';

    if (err.message.includes('User not found')) {
      statusCode = 404;
      errorMessage = `用户ID '${req.body.userId}' 不存在`;
    }

    res.status(statusCode).json({
      status: 'error',
      code: statusCode,
      message: errorMessage,
      details: process.env.NODE_ENV === 'development' ? err.message : undefined
    });
    return;
  }

});

export default mockAuthRouter;
